<template>
  <div class="profile-page">
    <div class="container">
      <div class="profile-header">
        <div class="profile-avatar">
          <img v-if="user?.avatarUrl" :src="user.avatarUrl" :alt="user.username" />
          <div v-else class="avatar-placeholder">{{ user?.username?.charAt(0).toUpperCase() }}</div>
          <button class="avatar-edit-btn" @click="showAvatarUpload = true">
            <span class="edit-icon">📷</span>
          </button>
        </div>
        
        <div class="profile-info">
          <h1 class="profile-name">{{ user?.username || '未设置' }}</h1>
          <p class="profile-email">{{ user?.email || '未设置邮箱' }}</p>
          <div class="profile-stats">
            <div class="stat">
              <span class="stat-value">{{ userStats.createdRoles || 0 }}</span>
              <span class="stat-label">创建角色</span>
            </div>
            <div class="stat">
              <span class="stat-value">{{ userStats.totalConversations || 0 }}</span>
              <span class="stat-label">对话次数</span>
            </div>
            <div class="stat">
              <span class="stat-value">{{ userStats.totalMessages || 0 }}</span>
              <span class="stat-label">消息总数</span>
            </div>
          </div>
        </div>
        
        <div class="profile-actions">
          <button class="edit-profile-btn" @click="showEditModal = true">编辑资料</button>
        </div>
      </div>
      
      <div class="profile-content">
        <div class="content-tabs">
          <button 
            v-for="tab in tabs" 
            :key="tab.id"
            :class="['tab-btn', { active: activeTab === tab.id }]"
            @click="activeTab = tab.id"
          >
            <span class="tab-icon">{{ tab.icon }}</span>
            {{ tab.name }}
          </button>
        </div>
        
        <div class="tab-content">
          <!-- 我的角色 -->
          <div v-if="activeTab === 'roles'" class="roles-section">
            <div class="section-header">
              <h2>我的角色</h2>
              <router-link to="/create-role" class="create-btn">创建角色</router-link>
            </div>
            
            <div v-if="myRolesLoading" class="loading-grid">
              <div v-for="i in 6" :key="i" class="role-card skeleton">
                <div class="skeleton-avatar"></div>
                <div class="skeleton-content">
                  <div class="skeleton-title"></div>
                  <div class="skeleton-desc"></div>
                </div>
              </div>
            </div>
            
            <div v-else-if="myRoles.length === 0" class="empty-state">
              <div class="empty-icon">🎭</div>
              <h3>还没有创建角色</h3>
              <p>创建你的第一个AI角色，开始精彩的对话体验</p>
              <router-link to="/create-role" class="create-btn">创建角色</router-link>
            </div>
            
            <div v-else class="roles-grid">
              <div v-for="role in myRoles" :key="role.id" class="role-card">
                <div class="role-avatar">
                  <img v-if="role.avatarUrl" :src="role.avatarUrl" :alt="role.name" />
                  <div v-else class="avatar-placeholder">{{ role.name.charAt(0) }}</div>
                </div>
                <div class="role-info">
                  <h3 class="role-name">{{ role.name }}</h3>
                  <p class="role-desc">{{ role.description || '暂无描述' }}</p>
                  <div class="role-stats">
                    <span class="stat">使用 {{ role.usageCount || 0 }} 次</span>
                    <span class="stat">评分 {{ role.averageRating || 0 }}</span>
                  </div>
                </div>
                <div class="role-actions">
                  <button class="action-btn" @click="editRole(role)">编辑</button>
                  <button class="action-btn" @click="startChat(role)">对话</button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 对话记录 -->
          <div v-if="activeTab === 'conversations'" class="conversations-section">
            <div class="section-header">
              <h2>对话记录</h2>
              <div class="conversation-filters">
                <select v-model="conversationFilter" @change="loadConversations">
                  <option value="">全部对话</option>
                  <option value="active">进行中</option>
                  <option value="archived">已归档</option>
                </select>
              </div>
            </div>
            
            <div v-if="conversationsLoading" class="loading-list">
              <div v-for="i in 5" :key="i" class="conversation-item skeleton">
                <div class="skeleton-avatar"></div>
                <div class="skeleton-content">
                  <div class="skeleton-title"></div>
                  <div class="skeleton-desc"></div>
                </div>
              </div>
            </div>
            
            <div v-else-if="conversations.length === 0" class="empty-state">
              <div class="empty-icon">💬</div>
              <h3>还没有对话记录</h3>
              <p>开始与AI角色对话，记录会显示在这里</p>
            </div>
            
            <div v-else class="conversations-list">
              <div 
                v-for="conv in conversations" 
                :key="conv.id" 
                class="conversation-item"
                @click="openConversation(conv)"
              >
                <div class="conv-avatar">
                  <img v-if="conv.roleAvatarUrl" :src="conv.roleAvatarUrl" :alt="conv.roleName" />
                  <div v-else class="avatar-placeholder">{{ conv.roleName?.charAt(0) }}</div>
                </div>
                <div class="conv-info">
                  <h3 class="conv-title">{{ conv.roleName }}</h3>
                  <p class="conv-preview">{{ conv.lastMessage || '暂无消息' }}</p>
                  <span class="conv-time">{{ formatTime(conv.updatedAt) }}</span>
                </div>
                <div class="conv-status" :class="conv.active ? 'active' : 'archived'">
                  {{ conv.active ? '进行中' : '已归档' }}
                </div>
              </div>
            </div>
          </div>
          
          <!-- 设置 -->
          <div v-if="activeTab === 'settings'" class="settings-section">
            <div class="settings-group">
              <h3>账户设置</h3>
              <div class="setting-item">
                <label>用户名</label>
                <input v-model="settings.username" type="text" class="setting-input" />
              </div>
              <div class="setting-item">
                <label>邮箱</label>
                <input v-model="settings.email" type="email" class="setting-input" />
              </div>
              <div class="setting-item">
                <label>新密码</label>
                <input v-model="settings.newPassword" type="password" class="setting-input" placeholder="留空则不修改" />
              </div>
            </div>
            
            <div class="settings-group">
              <h3>通知设置</h3>
              <div class="setting-item">
                <label>
                  <input v-model="settings.emailNotifications" type="checkbox" />
                  邮件通知
                </label>
              </div>
              <div class="setting-item">
                <label>
                  <input v-model="settings.pushNotifications" type="checkbox" />
                  推送通知
                </label>
              </div>
            </div>
            
            <div class="settings-actions">
              <button class="save-btn" @click="saveSettings">保存设置</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 编辑资料模态框 -->
    <div v-if="showEditModal" class="modal-overlay" @click="showEditModal = false">
      <div class="modal-content" @click.stop>
        <h2>编辑资料</h2>
        <form @submit.prevent="updateProfile">
          <div class="form-group">
            <label>用户名</label>
            <input v-model="editForm.username" type="text" required />
          </div>
          <div class="form-group">
            <label>邮箱</label>
            <input v-model="editForm.email" type="email" required />
          </div>
          <div class="form-actions">
            <button type="button" @click="showEditModal = false">取消</button>
            <button type="submit">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const user = ref(null)
const userStats = ref({})
const activeTab = ref('roles')
const showEditModal = ref(false)
const showAvatarUpload = ref(false)
const conversationFilter = ref('')

const myRoles = ref([])
const myRolesLoading = ref(false)
const conversations = ref([])
const conversationsLoading = ref(false)

const editForm = ref({
  username: '',
  email: ''
})

const settings = ref({
  username: '',
  email: '',
  newPassword: '',
  emailNotifications: true,
  pushNotifications: true
})

const tabs = [
  { id: 'roles', name: '我的角色', icon: '🎭' },
  { id: 'conversations', name: '对话记录', icon: '💬' },
  { id: 'settings', name: '设置', icon: '⚙️' }
]

const loadUser = async () => {
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      router.push('/login')
      return
    }
    
    // 从服务器获取最新用户信息
    const res = await fetch('/api/users/profile', {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    if (res.ok) {
      const data = await res.json()
      if (data.code === 0) {
        user.value = data.data
        editForm.value = { ...data.data }
        settings.value = { ...data.data }
      } else {
        router.push('/login')
        return
      }
    } else {
      router.push('/login')
      return
    }
  } catch (e) {
    console.error('加载用户信息失败', e)
    router.push('/login')
  }
}

const loadUserStats = async () => {
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) return
    
    const res = await fetch('/api/users/stats', {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    const data = await res.json()
    if (data.code === 0) {
      userStats.value = data.data
    }
  } catch (e) {
    console.error('加载用户统计失败', e)
  }
}

const loadMyRoles = async () => {
  myRolesLoading.value = true
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) return
    
    const res = await fetch('/api/roles/my', {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    const data = await res.json()
    if (data.code === 0) {
      myRoles.value = data.data || []
    }
  } catch (e) {
    console.error('加载我的角色失败', e)
  } finally {
    myRolesLoading.value = false
  }
}

const loadConversations = async () => {
  conversationsLoading.value = true
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) return
    
    const params = new URLSearchParams({
      pageNo: '1',
      pageSize: '20'
    })
    if (conversationFilter.value) {
      params.set('active', conversationFilter.value === 'active')
    }
    
    const res = await fetch(`/api/conversations?${params.toString()}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    const data = await res.json()
    if (data.code === 0) {
      conversations.value = data.data?.records || []
    }
  } catch (e) {
    console.error('加载对话记录失败', e)
  } finally {
    conversationsLoading.value = false
  }
}

const updateProfile = async () => {
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      router.push('/login')
      return
    }
    
    const res = await fetch('/api/users/profile', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(editForm.value)
    })
    
    const data = await res.json()
    if (data.code === 0) {
      user.value = data.data
      localStorage.setItem('auth_user', JSON.stringify(data.data))
      showEditModal.value = false
      alert('资料更新成功')
    } else {
      alert('更新失败：' + data.message)
    }
  } catch (e) {
    console.error('更新资料失败', e)
    alert('更新失败，请重试')
  }
}

const saveSettings = async () => {
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) return
    
    const res = await fetch('/api/users/settings', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(settings.value)
    })
    
    const data = await res.json()
    if (data.code === 0) {
      // 设置保存成功
    }
  } catch (e) {
    console.error('保存设置失败', e)
  }
}

const editRole = (role) => {
  router.push(`/edit-role/${role.id}`)
}

const startChat = (role) => {
  router.push(`/chat/${role.id}`)
}

const openConversation = (conv) => {
  router.push(`/chat/${conv.roleId}?conversationId=${conv.id}`)
}

const formatTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) return '昨天'
  if (diffDays < 7) return `${diffDays}天前`
  if (diffDays < 30) return `${Math.ceil(diffDays / 7)}周前`
  return date.toLocaleDateString()
}

onMounted(() => {
  loadUser()
  loadUserStats()
  loadMyRoles()
  loadConversations()
})
</script>

<style scoped>
.profile-page {
  height: 100%;
  background: #f8fafc;
  padding: 40px 0;
  overflow-y: auto;
}

.container {
  width: 100%;
  padding: 0 32px;
}

.profile-header {
  background: white;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  margin-bottom: 32px;
  display: flex;
  align-items: center;
  gap: 32px;
}

.profile-avatar {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.profile-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: white;
  font-size: 48px;
  font-weight: 600;
}

.avatar-edit-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 36px;
  height: 36px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.avatar-edit-btn:hover {
  background: #5a67d8;
  transform: scale(1.1);
}

.profile-info {
  flex: 1;
}

.profile-name {
  font-size: 2rem;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 4px;
}

.profile-email {
  color: #6b7280;
  margin-bottom: 20px;
}

.profile-stats {
  display: flex;
  gap: 32px;
}

.stat {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 1.5rem;
  font-weight: 700;
  color: #667eea;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.profile-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.edit-profile-btn {
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.edit-profile-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.profile-content {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  overflow: hidden;
}

.content-tabs {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
}

.tab-btn {
  flex: 1;
  padding: 16px 24px;
  background: none;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-weight: 500;
  color: #6b7280;
  transition: all 0.2s;
}

.tab-btn:hover {
  background: #f9fafb;
  color: #374151;
}

.tab-btn.active {
  color: #667eea;
  background: #f0f4ff;
  border-bottom: 2px solid #667eea;
}

.tab-icon {
  font-size: 18px;
}

.tab-content {
  padding: 32px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-header h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1f2937;
}

.create-btn {
  padding: 8px 16px;
  background: #667eea;
  color: white;
  text-decoration: none;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.create-btn:hover {
  background: #5a67d8;
}

.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.role-card {
  background: #f9fafb;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e5e7eb;
  transition: all 0.2s;
}

.role-card:hover {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.role-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-bottom: 12px;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.role-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.role-name {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.role-desc {
  color: #6b7280;
  font-size: 14px;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.role-stats {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.role-stats .stat {
  font-size: 12px;
  color: #6b7280;
}

.role-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  flex: 1;
  padding: 6px 12px;
  background: white;
  color: #374151;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn:hover {
  background: #f3f4f6;
}

.conversations-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.conversation-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f9fafb;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.conversation-item:hover {
  background: #f3f4f6;
}

.conv-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.conv-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.conv-info {
  flex: 1;
}

.conv-title {
  font-size: 1rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.conv-preview {
  color: #6b7280;
  font-size: 14px;
  margin-bottom: 4px;
}

.conv-time {
  color: #9ca3af;
  font-size: 12px;
}

.conv-status {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.conv-status.active {
  background: #dcfce7;
  color: #166534;
}

.conv-status.archived {
  background: #f3f4f6;
  color: #6b7280;
}

.settings-group {
  margin-bottom: 32px;
}

.settings-group h3 {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 16px;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #e5e7eb;
}

.setting-item label {
  font-weight: 500;
  color: #374151;
}

.setting-input {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  width: 200px;
}

.settings-actions {
  text-align: right;
}

.save-btn {
  padding: 12px 24px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.save-btn:hover {
  background: #5a67d8;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  padding: 32px;
  width: 90%;
}

.modal-content h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  font-weight: 500;
  color: #374151;
  margin-bottom: 6px;
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 16px;
  box-sizing: border-box;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
}

.form-actions button {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.form-actions button[type="button"] {
  background: #f3f4f6;
  color: #374151;
}

.form-actions button[type="submit"] {
  background: #667eea;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #6b7280;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 16px;
}

.empty-state h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.loading-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.loading-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.skeleton {
  background: #f3f4f6;
  border-radius: 12px;
  padding: 20px;
  animation: pulse 2s infinite;
}

.skeleton-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #e5e7eb;
  margin-bottom: 12px;
  animation: pulse 2s infinite;
}

.skeleton-content {
  flex: 1;
}

.skeleton-title {
  height: 16px;
  background: #e5e7eb;
  border-radius: 4px;
  margin-bottom: 8px;
  animation: pulse 2s infinite;
}

.skeleton-desc {
  height: 14px;
  background: #e5e7eb;
  border-radius: 4px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    text-align: center;
  }
  
  .profile-stats {
    justify-content: center;
  }
  
  .content-tabs {
    flex-direction: column;
  }
  
  .roles-grid {
    grid-template-columns: 1fr;
  }
  
  .setting-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .setting-input {
    width: 100%;
  }
}
</style>
